package tostring

import (
	"errors"
	"fmt"

	"gitee.com/dhcy/tencent_ddns/xlog"
	"github.com/bitly/go-simplejson"
)

var (
	ErrResponseDataIsNil = errors.New("response data is nil")
)

func toJson(rep []byte) (*simplejson.Json, error) {
	json, err := simplejson.NewJson(rep)
	if err != nil {
		return nil, fmt.Errorf("rsp data to json err:%v", err)
	}

	return json, nil
}

// GetPublicIp 解析获取公网IP响应信息
func GetPublicIp(rep []byte) (string, error) {
	json, err := toJson(rep)
	if err != nil {
		return "", err
	}
	ip, err := json.Get("ip").String()
	if err != nil {
		return "", err
	}
	if len(ip) == 0 {
		xlog.Warn(fmt.Sprintf("get public ip warn:%v", ErrResponseDataIsNil))
		return "", ErrResponseDataIsNil
	}
	return ip, nil
}

// SetDomainIp 解析设置域名响应信息
func SetDomainIp(rep []byte) error {
	json, err := toJson(rep)
	if err != nil {
		return err
	}
	code, err := json.Get("status").Get("code").String()
	if err != nil {
		return err
	}
	if code != "1" {
		xlog.Warn(fmt.Sprintf("set domain ip warn:%v", ErrResponseDataIsNil))
		return ErrResponseDataIsNil
	}
	return nil
}

// GetDomainIp 解析获取域名响应信息
func GetDomainIp(rep []byte) (id, ip, typ, lineId string, err error) {
	json, err := toJson(rep)
	if err != nil {
		return "", "", "", "", err
	}
	records := json.Get("records").GetIndex(0)
	id, err = records.Get("id").String()
	if err != nil {
		return "", "", "", "", err
	}
	ip, err = records.Get("value").String()
	if err != nil {
		return "", "", "", "", err
	}
	typ, err = records.Get("type").String()
	if err != nil {
		return "", "", "", "", err
	}
	lineId, err = records.Get("line_id").String()
	if err != nil {
		return "", "", "", "", err
	}
	if len(id) == 0 || len(ip) == 0 || len(typ) == 0 || len(lineId) == 0 {
		xlog.Warn(fmt.Sprintf("get domain ip warn:%v", ErrResponseDataIsNil))
		return "", "", "", "", ErrResponseDataIsNil
	}
	return id, ip, typ, lineId, nil
}
